package net.wofly.right.service.impl;

import com.github.stuxuhai.jpinyin.PinyinException;
import com.github.stuxuhai.jpinyin.PinyinFormat;
import com.github.stuxuhai.jpinyin.PinyinHelper;

import net.wofly.common.condition.Condition;
import net.wofly.common.condition.ConditionRelate;
import net.wofly.common.condition.ConditionUtil;
import net.wofly.common.condition.FilterCondition;
import net.wofly.common.condition.Operation;
import net.wofly.common.json.XiNiaoJSON;
import net.wofly.common.persistence.PageWrapper;
import net.wofly.common.util.CommonStatus;
import net.wofly.common.util.GeneralHelper;
import net.wofly.common.util.Identities;
import net.wofly.common.util.PageHelper;
import net.wofly.common.util.ResultCode;
import net.wofly.common.util.ReturnBean;
import net.wofly.finance.expense.domain.ExpenseAccount;
import net.wofly.right.domain.CustomInfo;
import net.wofly.right.domain.Organization;
import net.wofly.right.domain.ReceivingAddr;
import net.wofly.right.domain.User;
import net.wofly.right.domain.UserRole;
import net.wofly.right.dto.CustomDto;
import net.wofly.right.repository.OrganizationRepository;
import net.wofly.right.service.ICustomInfoService;
import net.wofly.right.service.IOrganizationService;
import net.wofly.right.service.IReceivingAddrService;
import net.wofly.right.service.IRoleService;
import net.wofly.right.service.IUserRoleService;
import net.wofly.right.service.IUserService;
import net.wofly.right.util.CustomType;
import net.wofly.right.util.RoleEnum;
import net.wofly.right.util.UserType;
import net.wofly.sale.stock.domain.Warehouse;
import net.wofly.sale.stock.service.IWarehouseService;
import net.wofly.sale.stock.util.WarehouseType;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.util.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@Service("iOrganizationService")
@Transactional
public class OrganizationServiceImpl implements IOrganizationService {
    private static final Logger logger = LoggerFactory.getLogger(OrganizationServiceImpl.class);
    @Autowired
    OrganizationRepository organizationRepository;
    
    @Autowired
    IUserService iUserService;
    @Autowired
    IReceivingAddrService iReceivingAddrService;
    
    @Autowired
    ICustomInfoService iCustomInfoService;
    
    @Autowired
    IWarehouseService iWarehouseService;
    @Autowired
    IUserRoleService iUserRoleService;
    @Autowired
    IRoleService iRoleService;

    
    @Override
    public Organization save(Organization entity) {
        try {
            if (StringUtils.isNotEmpty(entity.getOrganizationName())) {
                entity.setOrganizationNamePinYin(PinyinHelper.getShortPinyin(entity.getOrganizationName()));
            }
            if (StringUtils.isNotEmpty(entity.getLinkman())) {
                entity.setLinkmanPinYin(PinyinHelper.getShortPinyin(entity.getLinkman()));
            }
        } catch (PinyinException e) {
            e.printStackTrace();
        }
        return organizationRepository.save(entity);
    }
    
    @Override
    public void delete(Organization entity) {
        organizationRepository.delete(entity);
    }
    
    @Override
    public void delete(String key) {
        organizationRepository.delete(key);
    }
    
    @Override
    public Organization findOne(String key) {
        return organizationRepository.findOne(key);
    }
    
    @Override
    public List<Organization> save(List<Organization> entityList) {
        return (List<Organization>) organizationRepository.save(entityList);
    }
    
    @Override
    public List<Organization> findByStatus(Integer status) {
        return organizationRepository.findByStatus(status);
    }
    
    @Override
    public Organization findByOrganizationCode(String organizationCode) {
        return organizationRepository.findByOrganizationCode(organizationCode);
    }
    
    @Override
    public List<Organization> findAll() {
        return (List<Organization>) organizationRepository.findAll();
    }
    
    @Override
    public ReturnBean<Organization> addCompanyCustomer(Organization organization) {
        
        List<Organization> organizations = organizationRepository.findByOrganizationName(
                organization.getOrganizationName());
        if (!CollectionUtils.isEmpty(organizations)) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "添加企业客户失败，己有同名客户！");
        }
        
        List<User> dbCus = iUserService.findByMobileOrEmail(organization.getMobile(), "");
        if (!CollectionUtils.isEmpty(dbCus)) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "添加企业客户失败，该客户联系人手机号己注册！");
        }
        
        organization.setOrganizationID(Identities.uuid2());
        
        Integer maxOrganizationCode = organizationRepository.findMaxOrganizationCode();
        organization.setOrganizationCode(String.valueOf(maxOrganizationCode + 1));
        organization.setWarehouseFlag(0);
        organization.setStatus(1);
        organization.setModifyDate(System.currentTimeMillis());
        this.save(organization);
        
        User user = new User();
        user.setUserID(organization.getOrganizationID());
        user.setName(organization.getLinkman());
        user.setMobile(organization.getMobile());
        user.setAddr(organization.getAddr());
        user.setOrganizationID(organization.getOrganizationID());
        user.setRoleID(organization.getOrganizationType());
        user.setFollowUserID(organization.getOptUserID());
        user.setOptUser(organization.getOptUserID());
        user.setCustomType(2);
        user.setRegisterType(2);
        user.setRegisterWay(1);
        user.setWarehouseFlag(0);
        user.setIsLegal(1);
        user.setUserType(2);
        user.setModifyDate(System.currentTimeMillis());
        user.setRegisterTime(System.currentTimeMillis());
        iUserService.addUser(user);
        
        ReceivingAddr receivingAddr = new ReceivingAddr();
        receivingAddr.setReceivingAddrID(organization.getOrganizationID());
        receivingAddr.setUserID(organization.getOrganizationID());
        receivingAddr.setContacts(user.getName());
        receivingAddr.setMobile(user.getMobile());
        receivingAddr.setReceivingAddr(organization.getAddr());
        receivingAddr.setDefaultFlag(1);
        receivingAddr.setStatus(1);
        receivingAddr.setOptUserID(organization.getOrganizationID());
        receivingAddr.setModifyDate(organization.getModifyDate());
        iReceivingAddrService.save(receivingAddr);
        
        return new ReturnBean<Organization>(ResultCode.SUCCESS, "客户添加成功！", organization);
    }
    
    @Override
    public ReturnBean<User> getCustomer(String userID) {
        User user = iUserService.findOne(userID);
        
        if (null == user) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "客户信息不存在，请确定传递参数是否正确。");
        }
        
        if (user.getCustomType().equals(CustomType.companyCustom.getValue())) {
            Organization organization = organizationRepository.findOne(user.getOrganizationID());
            organization.setOrganizationTypeStr(RoleEnum.getName(Integer.parseInt(organization.getOrganizationType())));
            
            user.setOrganization(organization);
        }
        
        return new ReturnBean<User>(ResultCode.SUCCESS, "获取客户信息成功！", user);
    }
    
    @Override
    public ReturnBean<PageWrapper<Organization>> getCustomerByCondition(
            String name, String mobile, String customType, String followUserID, Integer pageNum, Integer pageSize) {


//		organizationRepository.findAll(spec, pageable)？

//		findAll(Specification specification, Pageable pageable);
        
        
        return null;
    }
    
    @Override
    public Map<String, Organization> getAllCampanyCustomerOrgMap() {
        Map<String, Organization> mapOrg = new HashMap<String, Organization>();
        List<Organization> orgs = organizationRepository.findByOrganizationType("201", 1);
        
        for (Organization org : orgs) {
            mapOrg.put(org.getOrganizationID(), org);
        }
        
        return mapOrg;
    }
    
    @Override
    public List<Organization> findByWarehouseFlagAndStatus(Integer warehouseFlag, Integer status) {
        return organizationRepository.findByWarehouseFlagAndStatus(warehouseFlag, status);
    }
    
    @Override
    public List<Organization> findByWarehouseFlagAndStatusAndOrganizationCodeNot(
            Integer warehouseFlag, Integer status, String organizationCode) {
        return organizationRepository.findByWarehouseFlagAndStatusAndOrganizationCodeNot(warehouseFlag, status,
                organizationCode);
    }
    
    @Override
    public List<Organization> findByOrganizationCodeStartingWithAndOrganizationCodeNot(String organizationCode) {
        return organizationRepository.findByOrganizationCodeStartingWithAndOrganizationCodeNot(organizationCode,
                organizationCode);
    }
    
    @Override
    public ReturnBean<String> saveCustomer(CustomDto customDto) {
        if (StringUtils.isEmpty(customDto.getOrganizationID())) {
            return saveCustomerByCustomDto(customDto);
        } else {
            return updateCustomerByCustomDto(customDto);
        }
        
    }
    
    private ReturnBean<String> saveCustomerByCustomDto(CustomDto customDto) {
        List<Organization> organizations = organizationRepository.findByOrganizationName(customDto.getCustomName());
        if (!CollectionUtils.isEmpty(organizations)) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "添加企业客户失败，己有同名客户！");
        }
        
        List<User> dbCustoms = iUserService.findByMobile(customDto.getMobile());
        if (null != dbCustoms && dbCustoms.size()>0) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "添加企业客户失败，该客户联系人手机号己注册！");
        }
        
        customDto.setOrganizationID(Identities.uuid2());
        
        Organization organization = new Organization();
        organization.setOrganizationID(customDto.getOrganizationID());
        
        Integer maxOrganizationCode = organizationRepository.findMaxOrganizationCode();
        if (null == maxOrganizationCode || maxOrganizationCode<=100200100) {
        		maxOrganizationCode = 100200100 ;
        }
        organization.setOrganizationCode(String.valueOf(maxOrganizationCode + 1));
        
        organization.setOrganizationName(customDto.getCustomName());
        organization.setLinkman(customDto.getLinkman());
        organization.setMobile(customDto.getMobile());
        organization.setAddr(customDto.getAddr());
        organization.setOrganizationType(customDto.getOrganizationType());
        
        organization.setWarehouseFlag(0);
        organization.setStatus(1);
        organization.setOptUserID(customDto.getOptUserID());
        organization.setModifyDate(System.currentTimeMillis());
        this.save(organization);
        
        User user = new User();
        user.setUserID(customDto.getOrganizationID());
        user.setName(organization.getLinkman());
        user.setMobile(organization.getMobile());
        user.setAddr(organization.getAddr());
        user.setOrganizationID(customDto.getOrganizationID());
        user.setRoleID(organization.getOrganizationType());
        user.setFollowUserID(customDto.getFollowUserID());
        user.setOptUser(organization.getOptUserID());
        user.setCustomType(UserType.单位客户.getValue());
        user.setUserType(UserType.单位客户.getValue());
        user.setRegisterType(2);
        user.setRegisterWay(1);
        user.setWarehouseFlag(0);
        user.setIsLegal(1);
        user.setUserType(2);
        user.setModifyDate(System.currentTimeMillis());
        user.setRegisterTime(System.currentTimeMillis());
        iUserService.addUser(user);
        
        ReceivingAddr receivingAddr = new ReceivingAddr();
        receivingAddr.setReceivingAddrID(customDto.getOrganizationID());
        receivingAddr.setUserID(organization.getOrganizationID());
        receivingAddr.setContacts(user.getName());
        receivingAddr.setMobile(user.getMobile());
        receivingAddr.setReceivingAddr(organization.getAddr());
        receivingAddr.setDefaultFlag(1);
        receivingAddr.setStatus(1);
        receivingAddr.setOptUserID(customDto.getOptUserID());
        receivingAddr.setModifyDate(organization.getModifyDate());
        iReceivingAddrService.save(receivingAddr);
        
        CustomInfo customInfo = new CustomInfo();
        customInfo.setCustomInfoID(customDto.getOrganizationID());
        customInfo.setOrganizationID(customDto.getOrganizationID());
        customInfo.setBusinessArea(customDto.getBusinessArea());
        customInfo.setHotelType(customDto.getHotelType());
        customInfo.setDiningTable(customDto.getDiningTable());
        customInfo.setCassetteDeck(customDto.getCassetteDeck());
        customInfo.setBigBox(customDto.getBigBox());
        customInfo.setMidBox(customDto.getMidBox());
        customInfo.setMinBox(customDto.getMinBox());
        
        int totalBox = customDto.getBigBox() + customDto.getMidBox() + customDto.getMinBox() ;
        if (totalBox>15) {
        		customInfo.setCustomerLevel("A");
        }else if (totalBox<=15 && totalBox>10) {
        		customInfo.setCustomerLevel("B");
        }else if (totalBox<=10 && totalBox>6) {
	    		customInfo.setCustomerLevel("C");
	    }else if (totalBox<=6 && totalBox>2) {
	    		customInfo.setCustomerLevel("D");
	    }else{
	    		customInfo.setCustomerLevel("E");
	    }
        
        customInfo.setCompetitorCooperationForm(customDto.getCompetitorCooperationForm());
        customInfo.setCompetitorProductAndPrise(customDto.getCompetitorProductAndPrise());
        customInfo.setCurrCooperationSituation(customDto.getCurrCooperationSituation());
        customInfo.setDescp(customDto.getDescp());
        customInfo.setFive(customDto.getFive());
        customInfo.setSix(customDto.getSix());
        customInfo.setTen(customDto.getTen());
        customInfo.setTwenty(customDto.getTwenty());
        customInfo.setRedBeautiful(customDto.getRedBeautiful());
        customInfo.setSilverBeautiful(customDto.getSilverBeautiful());
        customInfo.setRemark1(customDto.getRemark1());
        customInfo.setRemark2(customDto.getRemark2());
        customInfo.setRemark3(customDto.getRemark3());
        customInfo.setRemark4(customDto.getRemark4());
        iCustomInfoService.save(customInfo);
        
        Warehouse warehouse = new Warehouse();
        warehouse.setWarehouseID(customDto.getOrganizationID());
        warehouse.setWarehouseName(customDto.getCustomName() + " 的仓库");
        warehouse.setWarehouseType(WarehouseType.客户仓库.getValue().toString());
        warehouse.setStatus(1);
        warehouse.setModifyDate(organization.getModifyDate());
        
        iWarehouseService.save(warehouse);
        
        return new ReturnBean<>(ResultCode.SUCCESS, "客户添加成功！");
    }
    
    private ReturnBean<String> updateCustomerByCustomDto(CustomDto customDto) {
        Organization organization = organizationRepository.findOne(customDto.getOrganizationID());
        
        if (null == organization) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE,
                    "未找到相应的客户信息！ OrganizationID = " + customDto.getOrganizationID());
        }
        
        List<User> dbCustoms = iUserService.findByMobile(customDto.getMobile());
        if (null != dbCustoms && dbCustoms.size()>0) {
        		for(User dbCus:dbCustoms) {
        			if (!dbCus.getUserID().equals(customDto.getOrganizationID())){
            			return new ReturnBean<>(ResultCode.ERROR_SERVICE, "添加企业客户失败，该客户联系人手机号己注册！");
            		}
        		}
        }
        
        organization.setOrganizationName(customDto.getCustomName());
        organization.setLinkman(customDto.getLinkman());
        organization.setMobile(customDto.getMobile());
        organization.setAddr(customDto.getAddr());
        organization.setOrganizationType(customDto.getOrganizationType());
        
        organization.setModifyDate(System.currentTimeMillis());
        this.save(organization);
        
        User user = iUserService.findOne(customDto.getOrganizationID());
        if (null == user) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "未找到相应的客户信息！userID = " + customDto.getOrganizationID());
        }
        
        user.setName(organization.getLinkman());
        user.setMobile(organization.getMobile());
        user.setAddr(organization.getAddr());
        user.setModifyDate(System.currentTimeMillis());
        iUserService.addUser(user);
        
        ReceivingAddr receivingAddr = iReceivingAddrService.findOne(customDto.getOrganizationID());
        if (null == receivingAddr) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE,
                    "未找到相应的客户收货地址！receivingAddrID = " + customDto.getOrganizationID());
        }
        receivingAddr.setContacts(user.getName());
        receivingAddr.setMobile(user.getMobile());
        receivingAddr.setReceivingAddr(organization.getAddr());
        receivingAddr.setModifyDate(organization.getModifyDate());
        iReceivingAddrService.save(receivingAddr);
        
        CustomInfo customInfo = iCustomInfoService.findOne(organization.getOrganizationID());
        if (null == customInfo) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE,
                    "未找到相应的客户补充信息！customInfoID = " + customDto.getOrganizationID());
        }
        
        customInfo.setBusinessArea(customDto.getBusinessArea());
        customInfo.setHotelType(customDto.getHotelType());
        customInfo.setDiningTable(customDto.getDiningTable());
        customInfo.setCassetteDeck(customDto.getCassetteDeck());
        customInfo.setBigBox(customDto.getBigBox());
        customInfo.setMidBox(customDto.getMidBox());
        customInfo.setMinBox(customDto.getMinBox());
        customInfo.setCompetitorCooperationForm(customDto.getCompetitorCooperationForm());
        customInfo.setCompetitorProductAndPrise(customDto.getCompetitorProductAndPrise());
        customInfo.setCurrCooperationSituation(customDto.getCurrCooperationSituation());
        customInfo.setDescp(customDto.getDescp());
        customInfo.setFive(customDto.getFive());
        customInfo.setSix(customDto.getSix());
        customInfo.setTen(customDto.getTen());
        customInfo.setTwenty(customDto.getTwenty());
        customInfo.setRedBeautiful(customDto.getRedBeautiful());
        customInfo.setSilverBeautiful(customDto.getSilverBeautiful());
        
        int totalBox = customDto.getBigBox() + customDto.getMidBox() + customDto.getMinBox() ;
        if (totalBox>15) {
        		customInfo.setCustomerLevel("A");
        }else if (totalBox<=15 && totalBox>10) {
        		customInfo.setCustomerLevel("B");
        }else if (totalBox<=10 && totalBox>6) {
	    		customInfo.setCustomerLevel("C");
	    }else if (totalBox<=6 && totalBox>2) {
	    		customInfo.setCustomerLevel("D");
	    }else{
	    		customInfo.setCustomerLevel("E");
	    }
        
        iCustomInfoService.save(customInfo);
        
        return new ReturnBean<>(ResultCode.SUCCESS, "客户修改成功！");
    }
    
    @Override
    public ReturnBean<CustomDto> getCustomerDto(String customUserID) {
        CustomDto customDto = new CustomDto();
        
        Organization organization = organizationRepository.findOne(customUserID);
        
        if (null == organization) {
            return new ReturnBean<>(201, "你查找的客户信息不存在！ customUserID = " + customUserID);
        }
        
        customDto.setOrganizationID(organization.getOrganizationID());
        customDto.setAddr(organization.getAddr());
        customDto.setCustomName(organization.getOrganizationName());
        customDto.setLinkman(organization.getLinkman());
        customDto.setMobile(organization.getMobile());
        customDto.setOrganizationType(organization.getOrganizationType());
        customDto.setOrganizationTypeStr(RoleEnum.getName(Integer.parseInt(organization.getOrganizationType())));
        
        User user = iUserService.findOne(customUserID);
        if (null != user) {
            customDto.setFollowUserID(user.getFollowUserID());
            if (StringUtils.isNotEmpty(user.getFollowUserID())) {
                User followUser = iUserService.findOne(user.getFollowUserID());
                if (null != followUser) {
                    customDto.setFollowUserName(followUser.getName());
                }
            }
        }
        
        CustomInfo customInfo = iCustomInfoService.findOne(organization.getOrganizationID());
        if (null != customInfo) {
        		customDto.setBusinessArea(customInfo.getBusinessArea());
        		customDto.setHotelType(customInfo.getHotelType());
        		customDto.setDiningTable(customInfo.getDiningTable());
        		customDto.setCassetteDeck(customInfo.getCassetteDeck());
        		customDto.setBigBox(customInfo.getBigBox());
            customDto.setMidBox(customInfo.getMidBox());
            customDto.setMinBox(customInfo.getMinBox());
            customDto.setCompetitorCooperationForm(customInfo.getCompetitorCooperationForm());
            customDto.setCompetitorProductAndPrise(customInfo.getCompetitorProductAndPrise());
            customDto.setCurrCooperationSituation(customInfo.getCurrCooperationSituation());
            customDto.setDescp(customInfo.getDescp());
            customDto.setFive(customInfo.getFive());
            customDto.setSix(customInfo.getSix());
            customDto.setTen(customInfo.getTen());
            customDto.setTwenty(customInfo.getTwenty());
            customDto.setRedBeautiful(customInfo.getRedBeautiful());
            customDto.setSilverBeautiful(customInfo.getSilverBeautiful());
            customDto.setRemark1(customInfo.getRemark1());
            customDto.setRemark2(customInfo.getRemark2());
            customDto.setRemark3(customInfo.getRemark3());
            customDto.setRemark4(customInfo.getRemark4());
        }
        
        return new ReturnBean<>(ResultCode.SUCCESS, "获取客户信息成功！", customDto);
    }
    
    @Override
    public ReturnBean<PageWrapper<Organization>> findAllCustomerByPage(String customName, String linkMan, String mobile ,String organizationType , Integer pageNum, Integer pageSize) {
    		Condition condition = new Condition();
        List<FilterCondition> filterConditions = new ArrayList<FilterCondition>();
        
        String customNamePinYin = "";
        if (StringUtils.isNotEmpty(customName)) {
        		if (!GeneralHelper.isChinese(customName)) {
                customNamePinYin = customName;
                filterConditions.add(new FilterCondition(customNamePinYin, "organizationNamePinYin", ConditionRelate.and.name(), Operation.like.name(), 2)) ;
            }else {
            		filterConditions.add(new FilterCondition(customName, "organizationName", ConditionRelate.and.name(), Operation.like.name(), 2)) ;
            }
	    }
        
        if (StringUtils.isNotEmpty(linkMan)) {
        		filterConditions.add(new FilterCondition(linkMan.toString(), "linkman", ConditionRelate.and.name(), Operation.like.name(), 3)) ;
        }
        
        if (StringUtils.isNotEmpty(organizationType)) {
	    		filterConditions.add(new FilterCondition(organizationType, "organizationType", ConditionRelate.and.name(), Operation.eq.name(), 4)) ;
	    }
        
        if (StringUtils.isNotEmpty(mobile)) {
	    		filterConditions.add(new FilterCondition(mobile.toString(), "mobile", ConditionRelate.and.name(), Operation.like.name(), 5)) ;
	    } 
        
        filterConditions.add(new FilterCondition( "100200100" , "organizationCode", ConditionRelate.and.name(), Operation.gt.name(), 6)) ;
        
        condition.setFilterCondition(filterConditions);
        
        condition = ConditionUtil.buildCondition(XiNiaoJSON.toJSONString(condition), Organization.class).getResult();
        
        Pageable pageable = new PageRequest(pageNum - 1, pageSize, new Sort(Sort.Direction.DESC, "modifyDate"));
        
        Page<Organization> page = organizationRepository.findAll(condition.getSpecification(), pageable);
        
        transOrganization(page) ;
        
        return new ReturnBean<>(ResultCode.SUCCESS, "获取客户列表成功！", PageHelper.toPage(page));
    }
    
    /**
     * 根据组织机构编码查询子机构（不包括本身）
     *
     * @param orgCode
     * @param status
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public ReturnBean<PageWrapper<Organization>> findSubOrgsByOrgCode(
            String orgCode, Integer status, Integer pageNum, Integer pageSize) {
        
        Pageable pageable = new PageRequest(pageNum - 1, pageSize);
        Page<Organization> subOrgs = organizationRepository.findSubOrgsByOrgCode(orgCode, orgCode, status, pageable);
        
        return new ReturnBean<>(ResultCode.SUCCESS, "根据组织机构编码查询子机构成功", PageHelper.toPage(subOrgs));
    }
    
    /**
     * 修改组织机构
     *
     * @param organization
     * @return
     */
    @Override
    public ReturnBean<Organization> modifyOrganization(Organization organization) {
        if (iUserService.findOne(organization.getOptUserID()) == null) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "当前操作人员用户ID不正确");
        }
        Organization dbOrg = findOne(organization.getOrganizationID());
        if (dbOrg == null) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "组织机构ID不正确");
        }
        /*Organization dbOrg1 = findByOrganizationCode(organization.getOrganizationCode());
        if (dbOrg1 != null) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "组织机构编码已经存在");
        }*/
        organization.setOrganizationCode(dbOrg.getOrganizationCode());
        organization.setStatus(CommonStatus.有效.getValue());
        organization.setModifyDate(System.currentTimeMillis());
        
        return new ReturnBean<>(ResultCode.SUCCESS, "修改组织机构成功", save(organization));
    }
    
    /**
     * 根据组织机构查询人员
     *
     * @param orgCode
     * @param status
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public ReturnBean<PageWrapper<User>> findSubUsersByOrgCode(
            String orgCode, Integer status, Integer pageNum, Integer pageSize) {
        Organization dbOrg = findByOrganizationCode(orgCode);
        if (dbOrg == null) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "组织机构ID不正确");
        }
        
        Pageable pageable = new PageRequest(pageNum - 1, pageSize);
        Page<User> userPage = iUserService.findByOrganizationIDAndStatus(dbOrg.getOrganizationID(),
                status, pageable);

        List<User> userList = userPage.getContent();
        for (User user : userList) {
            if (user.getWarehouseFlag() != null) {
                if(user.getWarehouseFlag() == 0) {
                    user.setWarehouseFlagStr("没有");
                } else if(user.getWarehouseFlag() == 1) {
                    user.setWarehouseFlagStr("有");
                }
            }
            if (user.getWarehouseType() != null) {
                if(user.getWarehouseType() == 1) {
                    user.setWarehouseTypeStr("公司总仓库");
                } else if(user.getWarehouseType() == 2) {
                    user.setWarehouseTypeStr("部门仓库");
                } else if(user.getWarehouseType() == 3) {
                    user.setWarehouseTypeStr("个人仓库");
                }
            }

            List<UserRole> userRoles = iUserRoleService.findByUserID(user.getUserID());
            if (userRoles.size() > 0) {
                user.setRole(iRoleService.findOne(userRoles.get(0).getRoleID()));
            } else {
                logger.info("用户：{}的角色未获取到！", user.getUserID());
            }
        }
        
        return new ReturnBean<>(ResultCode.SUCCESS, "根据组织机构编码查询用户成功", PageHelper.toPage(userPage));
    }
    
    /**
     * 添加子机构
     *
     * @param parentOrganizationID
     * @param organization
     * @return
     */
    @Override
    public ReturnBean<Organization> addSubOrganization(
            String parentOrganizationID, Organization organization) {
        if (iUserService.findOne(organization.getOptUserID()) == null) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "当前操作人员用户ID不正确");
        }
        Organization dbOrg = findOne(parentOrganizationID);
        if (dbOrg == null) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "父级组织机构ID不正确");
        }
        Organization dbOrg1 = findByOrganizationCode(organization.getOrganizationCode());
        if (dbOrg1 != null) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "组织机构编码已经存在，请重新填写组织机构编码");
        }
        
        if (!dbOrg.getOrganizationCode().equals(
                organization.getOrganizationCode().substring(0, organization.getOrganizationCode().length() - 3))) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "组织机构编码规则错误，不能和父级机构关联上");
        }
        
        organization.setOrganizationID(Identities.uuid2());
        organization.setStatus(CommonStatus.有效.getValue());
        organization.setModifyDate(System.currentTimeMillis());
        
        return new ReturnBean<>(ResultCode.SUCCESS, "添加子机构成功", save(organization));
    }
    
    /**
     * 删除机构
     *
     * @param organizationID
     * @return
     */
    @Override
    public ReturnBean<Void> deleteOrganization(String organizationID) {
        Organization dbOrg = findOne(organizationID);
        if (dbOrg == null) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "组织机构ID不正确");
        }
        //  Q:删除机构时，有子机构或者机构下有人员是否允许删除  A:不允许删除
        List<Organization> organizations =
                findByOrganizationCodeStartingWithAndOrganizationCodeNot(dbOrg.getOrganizationCode());
        
        if (!CollectionUtils.isEmpty(organizations)) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "组织机构下有子机构或人员，不能删除");
        }
        
        List<User> users = iUserService.findByOrganizationID(organizationID);
        if (!CollectionUtils.isEmpty(users)) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "组织机构下有子机构或人员，不能删除");
        }
        
        dbOrg.setStatus(CommonStatus.无效.getValue());
        dbOrg.setModifyDate(System.currentTimeMillis());
        save(dbOrg);
        return new ReturnBean<>(ResultCode.SUCCESS, "删除组织机构成功");
    }

	@Override
	public ReturnBean<List<Organization>> findOrgTreeByOrgCode(String orgCode, Integer status) {

        List<Organization> orgs = organizationRepository.findOrgsByOrgCode(orgCode,  status) ;
        if (null == orgs || orgs.isEmpty()) {
            return new ReturnBean<>(ResultCode.SUCCESS, "获取树形组织机构成功" ,null);
        }

        Predicate<Organization> contain = n -> n.getOrganizationCode().equals(orgCode);
        List<Organization> topList = orgs.stream().filter(contain).collect(Collectors.toList());

        if (null == topList || topList.isEmpty()) {
            return new ReturnBean<>(ResultCode.SUCCESS, "获取树形组织机构成功" ,null);
        }

        filterOrgTree(topList, orgs, 0);

        return new ReturnBean<>(ResultCode.SUCCESS, "根据组织机构编码查询子机构成功", topList);
	}

    private void  filterOrgTree(List<Organization> loopList, List<Organization> orgs, int listLen){
        if (listLen == orgs.size()) {
            return;
        }

        Predicate<Organization> tmpContain1 ;
        Predicate<Organization> tmpContain2 ;

        for(Organization org : loopList) {
            tmpContain1 = n -> n.getOrganizationCode().startsWith(org.getOrganizationCode());
            tmpContain2 = n -> org.getOrganizationCode().length() + 3 == n.getOrganizationCode().length();
            List<Organization> subOrgList = orgs.stream().filter(tmpContain1.and(tmpContain2)).collect(Collectors.toList());
            if (subOrgList.size() == 0) {
                continue;
            }
            org.setSubOrgList(subOrgList);
            listLen += subOrgList.size();
            filterOrgTree(subOrgList, orgs, listLen);
        }
    }

	public static void main(String[] args) {  
        
        //初始化list集合  
        List<String> list = new ArrayList<String>();  
        list.add("测试数据1");  
        list.add("测试数据2");  
        list.add("测试数据3");  
        list.add("测试数据12");  
        list.add("test数据1"); 
        list.add("test数据2"); 
          
        //使用λ表达式遍历集合  
        list.forEach(s -> System.out.println(s));  
          
        //结合Predicate使用和过滤条件筛选元素  
        Predicate<String> contain1 = n -> n.contains("1");  
        Predicate<String> contain2 = n -> n.contains("2");  
        Predicate<String> contain3 = n -> n.startsWith("test");  
        
        list.stream().filter(s -> contain3.test(s)).forEach(n -> System.out.println(n));  
          
        //根据条件遍历集合  
        list.stream().filter(contain1).forEach(n -> System.out.println(n));  
        list.stream().filter(s -> contain1.test(s)).forEach(s -> System.out.println(s));  
        list.stream().filter(contain1.and(contain2)).forEach(n -> System.out.println(n));  
        list.stream().filter(contain1.or(contain2)).forEach(n -> System.out.println(n));  
          
        //将过滤后的元素重新放到一个集合中  
        List<String> newList = list.stream().filter(contain1.and(contain2)).collect(Collectors.toList());  
          
        newList.forEach(s -> System.out.println(s));  
  
    }

	@Override
	public ReturnBean<PageWrapper<Organization>> findMyCustomerByPage(String salesUserID, String customName,
			String linkMan, String mobile, String organizationType, Integer pageNum, Integer pageSize) {
		String customNamePinYin = "";
		String linkManPinYin = "";
		if (StringUtils.isNotEmpty(customName)) {
        		if (!GeneralHelper.isChinese(customName)) {
                customNamePinYin = customName;
                customName = "";
            }
        } else {
            customName = "";
	    }
		        
        if (StringUtils.isNotEmpty(linkMan)) {
            if (!GeneralHelper.isChinese(linkMan)) {
                linkManPinYin = linkMan;
                linkMan = "";
            }
        }
        
        if (StringUtils.isEmpty(organizationType)) {
        		organizationType = "" ;
        }
		
		Sort sort = new Sort(Sort.Direction.DESC, "modifyDate");
		Pageable pageable = new PageRequest(pageNum - 1, pageSize, sort);

		Page<Organization> oPage;
		oPage = this.organizationRepository.findMyCustomer(salesUserID, customName, customNamePinYin,linkMan, linkManPinYin, mobile, organizationType , pageable);
		
		transOrganization(oPage) ;
		
        return new ReturnBean<>(ResultCode.SUCCESS, "获取我的客户列表成功！", PageHelper.toPage(oPage));
	}  
	
	private void transOrganization(Page<Organization> oPage) {
		if (null==oPage) {
			return ;
		}
		
		List<Organization> organizations = oPage.getContent() ;
		
		if (null==organizations || organizations.isEmpty()) {
			return ;
		}
		
		User user ;
		User followUser ;
		for(Organization org:organizations) {
			org.setOrganizationTypeStr(RoleEnum.getName(Integer.valueOf(org.getOrganizationType())));
			org.setCustomInfo(iCustomInfoService.findOne(org.getOrganizationID())) ;
			
			user = iUserService.findOne(org.getOrganizationID()) ;
			if (null!=user) {
				if (StringUtils.isNotEmpty(user.getFollowUserID())) {
					followUser = iUserService.findOne(user.getFollowUserID()) ;
					org.setFollowUser(followUser);
				}
			}
		}
	}

}

